package org.lsy.k8s_assignment.service;

import lombok.extern.slf4j.Slf4j;
import org.lsy.k8s_assignment.dao.StudentRepository;
import org.lsy.k8s_assignment.model.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author SHIYUAN
 * @version 1.0
 */
@Service
@Slf4j
public class StudentService {

    private final StudentRepository studentRepository;

    @Autowired
    StudentService(StudentRepository studentRepository) {
        this.studentRepository = studentRepository;
    }

    /**
     * 获取全部学生
     * @return 全部学生
     */
    public List<Student> findAll() {
        return studentRepository.findAll();
    }

    /**
     * 保存学生
     * @param student 学生信息
     * @return 是否成功
     */
    public boolean saveStudent(Student student) {
        boolean result = true;
        try {
            studentRepository.save(student);
        } catch (Exception e) {
            log.error("保存学生失败:{},原因:{}", student, e.toString());
            result = false;
        }
        return result;
    }

    /**
     * 更新学生
     * @param id 学生id
     * @param age 学生年龄
     * @return 是否成功
     */
    public boolean updateStudent(Integer id, Integer age) {
        boolean result = true;
        try {
            Student student = studentRepository.findById(id).orElse(null);
            if (student == null) {
                log.error("学生不存在:{}", id);
                return false;
            } else {
                student.setAge(age);
                studentRepository.save(student);
            }
        } catch (Exception e) {
            log.error("更新学生失败:{},原因:{}", id, e.toString());
            result = false;
        }
        return result;
    }

    /**
     * 删除学生
     * @param id 学生id
     * @return 是否成功
     */
    public boolean deleteStudent(Integer id) {
        boolean result = true;
        try {
            studentRepository.deleteById(id);
        } catch (Exception e) {
            log.error("删除学生失败:{},原因:{}", id, e.toString());
            result = false;
        }
        return result;
    }

}
